import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from celery_tasks.yuntongxun.ccp_sms import CCP
from ihome_project.libs.captcha.captcha import captcha

from django import http
from django.views import View
import json
import logging
logger = logging.getLogger('django')
from django_redis import get_redis_connection

class ImageCodeView(View):

    # 获取图片验证码
    def get(self, request,cur):
        # json_dict = json.loads(request.body.decode())
        # cur = json_dict.get('cur')
        # print(cur)
        # 1.调用工具类 captcha 生成图形验证码
        text, image = captcha.generate_captcha()

        # 2.链接 redis, 获取链接对象
        redis_conn = get_redis_connection('verify_code')

        # 3.利用链接对象, 保存数据到 redis, 使用 setex 函数设置有效期
        redis_conn.setex('img_%s' % cur, 300, text)

        # result = redis_conn.get('img_%s' % cur)
        print(cur)

        # 4.返回(图片)
        return HttpResponse(image,
                            content_type='image/jpg')


class SMSCodeView(View):
    def post(self,request):
        """短信验证接口"""
        # 接受json参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        # # 链接redis2号库
        redis_conn = get_redis_connection('verify_code')
        # # 进入函数后, 先获取存储在 redis 中的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # # 查看数据是否存在, 如果存在, 说明60s没过, 返回
        if send_flag:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '发送短信过于频繁'})

        id = json_dict.get('id')
        print(id)
        text = json_dict.get('text')
        # 校验参数
        if not all([mobile,id,text]):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '缺少参数'
            })

        # # 提取图形验证码
        # result = redis_conn.get('img_%s' % cur)
        # print(result)
        image_code_server = redis_conn.get('img_e')
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code': 400,
                                      'errmsg': '图形验证码失效'})
        # # 删除redis图形验证码，避免恶意测试
        try:
            redis_conn.delete('img_%s'%id)
        except Exception as e:
            logger.error(e)
        # # 对比图形验证码
        image_code_server = image_code_server.decode()
        if text.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '输入图形验证码有误'})
        # 随机生成6位数验证吗
        sms_code = '%06d'%random.randint(0,999999)
        logger.info(sms_code)
        # 存到redis设置有效期5分钟
        # redis_conn.setex('sms_%s'%mobile,300,sms_code)
        # 创建管道
        pl = redis_conn.pipeline()

        pl.setex('sms_%s'%mobile,300,sms_code)
        pl.setex('send_flag_%s'%mobile,60,1)

        # 执行管道:
        pl.execute()



        # 短信模板
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 10. 响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '发送短信成功'})

        pass